#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jobs.h"

Job* job_list = NULL;           // 链表头部
static int job_counter = 1;     // 自增编号计数器

// 添加后台任务
void add_job(pid_t pid, const char* cmd) {
    Job* new_job = (Job*)malloc(sizeof(Job));
    if (!new_job) {
        perror("malloc failed");
        return;
    }

    new_job->id = job_counter++;
    new_job->pid = pid;
    strncpy(new_job->command, cmd, sizeof(new_job->command));
    new_job->command[sizeof(new_job->command) - 1] = '\0'; // 确保以 '\0' 结尾
    new_job->next = job_list;
    job_list = new_job;
}

// 删除任务
void remove_job(pid_t pid) {
    Job** cur = &job_list;
    while (*cur) {
        if ((*cur)->pid == pid) {
            Job* temp = *cur;
            *cur = (*cur)->next;
            free(temp);
            return;
        }
        cur = &((*cur)->next);
    }
}

// 打印所有后台任务
void print_jobs(void) {
    // 1. 把链表反转存到数组
    Job* arr[100];
    int count = 0;

    Job* cur = job_list;
    while (cur && count < 100) {
        arr[count++] = cur;
        cur = cur->next;
    }

    // 2. 倒序输出
    for (int i = count - 1; i >= 0; --i) {
        printf("[%%%2d] PID: %-6d CMD: %s\n", arr[i]->id, arr[i]->pid, arr[i]->command);
    }
}


